<template>
  <div class='swiper-container'>
    <ul class='swiper-wrapper'>
      <li class='swiper-slide' v-for='item of swiper' :key='item.id'>
        <img class='img_c1' :src='item.imgUrl' alt=''>
      </li>
    </ul>
    <!-- Add Pagination -->
    <div class='swiper-pagination'></div>
  </div>
</template>

<script>
import Swiper from 'swiper'
import 'swiper/dist/css/swiper.min.css'
import { mapState } from 'vuex'

export default {
  name: 'HomeSwiper',
  props: {
    swiper: Array
  },
  data () {
    return {
      mySwiper: null
    }
  },
  computed: {
    ...mapState(['swipers'])
  },
  mounted () {
    // alert('第五步')
    this.$nextTick(() => {
      this._initSwiper() // 页面一加载拉去数据创建节点
    })
  },
  methods: {
    _initSwiper () { // 创建节点
      // alert('第一步')
      this.mySwiper = new Swiper('.swiper-container', {
        loop: true, // 循环模式选项
        autoplay: { // 自动切换
          disableOnInteraction: false // 用户操作swiper之后,是否禁止autoplay.默认为true:停止
        },
        pagination: {
          el: '.swiper-pagination',
          clickable: true
        },
        observer: true, // 修改swiper自己或子元素时，自动初始化swiper
        observeParents: true // 修改swiper的父元素时，自动初始化swiper
      })
    },
    _updateSwiper () {
      // alert('第二步')
      this.$nextTick(() => { // swiper动态更新
        this.mySwiper.update(true) // swiper update的方法
      })
    },
    swiperUpdate () {
      // alert('第三步')
      if (this.mySwiper) { // 节点存在
        this._updateSwiper() // 更新
      } else {
        this._initSwiper() // 创建
      }
    }
  },
  watch: {
    // 通过props传来的数据 和 组件一加载节点就创建成功 二者不是同步，实时监听的swiper(传递的值)的变化
    swiper () {
      // alert('第四步')
      this.swiperUpdate()
    }
  }
}
</script>

<style lang='stylus' scoped>
  .swiper-container >>> .swiper-pagination-bullet-active
    background: #fff!important
    opacity 1!important
  .swiper-container >>> .swiper-pagination-bullet
    opacity .6
    width 15px
    height 15px
    background gray
  .swiper-container >>> .swiper-container-horizontal > .swiper-pagination-bullets
    bottom: 16px
  .swiper-container
    margin-top 96px
    width: 100%
    height: 400px
    .swiper-wrapper
      width: 100%
      height: 100%
    .swiper-slide
      width: 100%
      height: 100%
      img
        width: 100%
        height: 100%
</style>
